package homework.score.display;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class TablePrinter implements IPrinter {

    @Override
    public String format(List<Map<String, String>> objectsAttrs) {
        StringBuilder builder = new StringBuilder();

        Map<String, Integer> columnsMaxWidth = new HashMap<String, Integer>();

        for (Map<String, String> attrs : objectsAttrs) {

            Object[] entries = attrs.entrySet().toArray();

            for (int i=0;i<attrs.size();i++) {
                Map.Entry<String, String> entry = (Map.Entry) entries[i];
                String key = entry.getKey();
                String value = entry.getValue();

//                if (columnsMaxWidth.get(entry.getKey()) == null) {
//                    columnsMaxWidth.put(entry.getKey(), 0);
//                }

                columnsMaxWidth.putIfAbsent(key, 0);

                if (value.length() > columnsMaxWidth.get(key)) {
                    columnsMaxWidth.put(key, value.length());
                }
            }
        }

        Set<String> keys = columnsMaxWidth.keySet();

        // 打印标题
        for (String key : keys) {
            int width = columnsMaxWidth.get(key);

            // 标题可能比值长
            if (width < key.length()) {
                width = key.length();
                columnsMaxWidth.put(key, width);
            }

            String fmt = String.format("%%%ds", width + 2);
            builder.append(String.format(fmt, key));
        }
        builder.append("\n");

        for (Map<String, String> attrs : objectsAttrs) {

            for (String key : keys) {
                int width = columnsMaxWidth.get(key);
                String fmt = String.format("%%%ds", width + 2);

                builder.append(String.format(fmt, attrs.get(key)));
            }

            builder.append("\n");
        }

        return builder.toString();
    }
}
